package br.com.jk.produto;

import br.com.jk.email.EmailTableModel;
import br.com.jk.empresa.Empresa;
import br.com.jk.empresa.EmpresaJDialog;
import br.com.jk.master.Master;
import br.com.jk.telefone.TelefoneTableModel;
import br.com.jk.usuario.jtable.UsuarioJTableUtil;
import br.com.jk.util.ControllerException;
import br.com.jk.util.Util;
import java.awt.event.KeyEvent;
import java.math.BigDecimal;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

/**
 *
 * @author camilo
 */
public class ProdutoJDialog extends javax.swing.JDialog {

  private static ProdutoJDialog dialog;
  private int idEmpresa;
  // Model da tabela
  ProdutoTableModel prodTm = new ProdutoTableModel();
  TelefoneTableModel telTm = new TelefoneTableModel();
  EmailTableModel emTm = new EmailTableModel();
  ProdutoController control = new ProdutoController();
  List<Produto> lstForn;
  private int idEnd;
//  atributos utilizados nas pesquisas externas
  private JTextField idPesquisa;
  private JTextField razaoPesquisa;
  private boolean modoConsultaExt;

  public static ProdutoJDialog getInstance(java.awt.Frame parent, boolean modal) {
    if (dialog == null) {
      dialog = new ProdutoJDialog(parent, modal);
    }
    return dialog;
  }

  public static ProdutoJDialog getInstance(java.awt.Frame parent, boolean modal, JTextField id, JTextField razao) {
    if (dialog == null) {
      dialog = new ProdutoJDialog(parent, modal, id, razao);
    }
    return dialog;
  }

  /**
   * Creates new form FornecedorJDialog
   */
  private ProdutoJDialog(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
    criaModel();

    setLocationRelativeTo(null);
    listar();
    jlFiltro.setVisible(false);
  }

  private ProdutoJDialog(java.awt.Frame parent, boolean modal, JTextField id, JTextField razao) {
    super(parent, modal);
    this.idPesquisa = id;
    this.razaoPesquisa = razao;
    this.modoConsultaExt = true;

    initComponents();
    criaModel();

    setLocationRelativeTo(null);
    listar();
    jlFiltro.setVisible(false);
  }

  private void criaModel() {
    jtProduto.setModel(prodTm);

    prodTm.sorter(jtProduto, prodTm);

    UsuarioJTableUtil.alteraJTable(prodTm, jtProduto, "jtProduto", Master.usuarioLogado);
  }

  /**
   * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this
   * code. The content of this method is always regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {
    java.awt.GridBagConstraints gridBagConstraints;

    JtbMaster = new javax.swing.JToolBar();
    JbNovo = new javax.swing.JButton();
    JbSalvar = new javax.swing.JButton();
    JbEditar = new javax.swing.JButton();
    JbCancelar = new javax.swing.JButton();
    JbExcluir = new javax.swing.JButton();
    JbBuscar = new javax.swing.JButton();
    JbRelatorio = new javax.swing.JButton();
    jSeparator1 = new javax.swing.JToolBar.Separator();
    JbRefresh = new javax.swing.JButton();
    jlFiltro = new javax.swing.JLabel();
    jSeparator2 = new javax.swing.JToolBar.Separator();
    jbJTable = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    jtProduto = new javax.swing.JTable();
    jpDados = new javax.swing.JPanel();
    jLabel2 = new javax.swing.JLabel();
    jtfId = new javax.swing.JTextField();
    jLabel1 = new javax.swing.JLabel();
    jtfCodEan = new javax.swing.JTextField();
    jLabel3 = new javax.swing.JLabel();
    jtfDescricao = new javax.swing.JTextField();
    jLabel4 = new javax.swing.JLabel();
    jtfEmb = new javax.swing.JTextField();
    jLabel5 = new javax.swing.JLabel();
    jtfPrecoVenda = new javax.swing.JTextField();
    jLabel7 = new javax.swing.JLabel();
    jtfIdEmpresa = new javax.swing.JTextField();
    jtfEmpresa = new javax.swing.JTextField();
    jcbAtivo = new javax.swing.JCheckBox();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Cadastro de produtos");
    addWindowListener(new java.awt.event.WindowAdapter() {
      public void windowClosed(java.awt.event.WindowEvent evt) {
        formWindowClosed(evt);
      }
    });

    JtbMaster.setRollover(true);

    JbNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-new.png"))); // NOI18N
    JbNovo.setToolTipText("Novo Registro");
    JbNovo.setFocusable(false);
    JbNovo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbNovo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbNovo.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbNovoActionPerformed(evt);
      }
    });
    JtbMaster.add(JbNovo);

    JbSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-save-hd.png"))); // NOI18N
    JbSalvar.setToolTipText("Salvar Registro");
    JbSalvar.setEnabled(false);
    JbSalvar.setFocusable(false);
    JbSalvar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbSalvar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbSalvar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbSalvarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbSalvar);

    JbEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-edit.png"))); // NOI18N
    JbEditar.setToolTipText("Alterar registro");
    JbEditar.setEnabled(false);
    JbEditar.setFocusable(false);
    JbEditar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbEditar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbEditar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbEditarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbEditar);

    JbCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/dialog-cancel.png"))); // NOI18N
    JbCancelar.setToolTipText("Cancelar");
    JbCancelar.setEnabled(false);
    JbCancelar.setFocusable(false);
    JbCancelar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbCancelar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbCancelar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbCancelarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbCancelar);

    JbExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/archive-remove.png"))); // NOI18N
    JbExcluir.setToolTipText("Excluir");
    JbExcluir.setEnabled(false);
    JbExcluir.setFocusable(false);
    JbExcluir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbExcluir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbExcluir.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbExcluirActionPerformed(evt);
      }
    });
    JtbMaster.add(JbExcluir);

    JbBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/edit-find.png"))); // NOI18N
    JbBuscar.setToolTipText("Buscar");
    JbBuscar.setEnabled(false);
    JbBuscar.setFocusable(false);
    JbBuscar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbBuscar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbBuscar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbBuscarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbBuscar);

    JbRelatorio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/report.png"))); // NOI18N
    JbRelatorio.setToolTipText("Relatórios");
    JbRelatorio.setEnabled(false);
    JbRelatorio.setFocusable(false);
    JbRelatorio.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbRelatorio.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbRelatorio.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbRelatorioActionPerformed(evt);
      }
    });
    JtbMaster.add(JbRelatorio);
    JtbMaster.add(jSeparator1);

    JbRefresh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/view-refresh.png"))); // NOI18N
    JbRefresh.setToolTipText("Atualizar registros da lista");
    JbRefresh.setFocusable(false);
    JbRefresh.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbRefresh.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbRefresh.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbRefreshActionPerformed(evt);
      }
    });
    JtbMaster.add(JbRefresh);

    jlFiltro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/task-attempt.png"))); // NOI18N
    JtbMaster.add(jlFiltro);
    JtbMaster.add(jSeparator2);

    jbJTable.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/view-form-table.png"))); // NOI18N
    jbJTable.setToolTipText("Grava as informações da JTable");
    jbJTable.setFocusable(false);
    jbJTable.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    jbJTable.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    jbJTable.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jbJTableActionPerformed(evt);
      }
    });
    JtbMaster.add(jbJTable);

    /*jtProduto.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
      public void valueChanged(ListSelectionEvent evt){
        if (evt.getValueIsAdjusting()){
          return;
        }
        int selected = jtProduto.getSelectedRow();
        fControl.selecionado();
      }
    });

    jtProduto.getColumnModel().getSelectionModel().addListSelectionListener(new ListSelectionListener(){
      public void valueChanged(ListSelectionEvent evt){
        if (evt.getValueIsAdjusting()){
          return;
        }
        int selected = jtProduto.getSelectedColumn();
        fControl.selecionado();
      }
    });*/
    jtProduto.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
    jtProduto.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mouseClicked(java.awt.event.MouseEvent evt) {
        jtProdutoMouseClicked(evt);
      }
    });
    jtProduto.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtProdutoKeyPressed(evt);
      }
    });
    jScrollPane1.setViewportView(jtProduto);

    jpDados.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder(""), "Dados"));
    java.awt.GridBagLayout jpDadosLayout = new java.awt.GridBagLayout();
    jpDadosLayout.columnWidths = new int[] {80, 10, 80, 10, 150};
    jpDados.setLayout(jpDadosLayout);

    jLabel2.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel2.setText("Id");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jLabel2, gridBagConstraints);

    jtfId.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfId.setEnabled(false);
    jtfId.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfIdKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfId, gridBagConstraints);

    jLabel1.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel1.setText("Cod. EAN");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 4;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jLabel1, gridBagConstraints);

    jtfCodEan.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfCodEan.setEnabled(false);
    jtfCodEan.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfCodEanKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 4;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfCodEan, gridBagConstraints);

    jLabel3.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel3.setText("Descrição");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jLabel3, gridBagConstraints);

    jtfDescricao.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfDescricao.setEnabled(false);
    jtfDescricao.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfDescricaoKeyPressed(evt);
      }
      public void keyReleased(java.awt.event.KeyEvent evt) {
        jtfDescricaoKeyReleased(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.gridwidth = 6;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfDescricao, gridBagConstraints);

    jLabel4.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel4.setText("Emb");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jLabel4, gridBagConstraints);

    jtfEmb.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfEmb.setEnabled(false);
    jtfEmb.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusLost(java.awt.event.FocusEvent evt) {
        jtfEmbFocusLost(evt);
      }
    });
    jtfEmb.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfEmbKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfEmb, gridBagConstraints);

    jLabel5.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel5.setText("Preço Venda");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 6;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jLabel5, gridBagConstraints);

    jtfPrecoVenda.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfPrecoVenda.setEnabled(false);
    jtfPrecoVenda.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfPrecoVendaKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 7;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfPrecoVenda, gridBagConstraints);

    jLabel7.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel7.setText("Empresa");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 4;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jLabel7, gridBagConstraints);

    jtfIdEmpresa.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfIdEmpresa.setEnabled(false);
    jtfIdEmpresa.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfIdEmpresaKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 5;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints.ipadx = 27;
    jpDados.add(jtfIdEmpresa, gridBagConstraints);

    jtfEmpresa.setEditable(false);
    jtfEmpresa.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfEmpresa.setEnabled(false);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 5;
    gridBagConstraints.gridwidth = 4;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfEmpresa, gridBagConstraints);

    jcbAtivo.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jcbAtivo.setSelected(true);
    jcbAtivo.setText("Ativo");
    jcbAtivo.setToolTipText("Marque essa opção caso o fornecedor seja Pessoa Física");
    jcbAtivo.setEnabled(false);
    jcbAtivo.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jcbAtivoKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 4;
    gridBagConstraints.gridy = 7;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
    jpDados.add(jcbAtivo, gridBagConstraints);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addGap(4, 4, 4)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jpDados, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
          .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 556, Short.MAX_VALUE)))
      .addComponent(JtbMaster, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addComponent(JtbMaster, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jpDados, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addGap(13, 13, 13))
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void JbNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbNovoActionPerformed
    novo();
  }//GEN-LAST:event_JbNovoActionPerformed

  private void JbSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbSalvarActionPerformed
    salvar();
  }//GEN-LAST:event_JbSalvarActionPerformed

  private void JbEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbEditarActionPerformed
    editar();
  }//GEN-LAST:event_JbEditarActionPerformed

  private void JbCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbCancelarActionPerformed
    cancelar();
  }//GEN-LAST:event_JbCancelarActionPerformed

  private void JbExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbExcluirActionPerformed
    excluir();
  }//GEN-LAST:event_JbExcluirActionPerformed

  private void JbBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbBuscarActionPerformed
    control.pesquisar();
  }//GEN-LAST:event_JbBuscarActionPerformed

  private void JbRelatorioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbRelatorioActionPerformed
    try {
//      Master.setJpbStatusIndeterminate(true);
//      Master.setTextJlStatus("Gerando relatório...");
      ThreadReport thReport = new ThreadReport();
      thReport.start();

    } catch (Exception e) {
      Util.msgErro(e, "Erro ao gerar o relatório");
    }
  }//GEN-LAST:event_JbRelatorioActionPerformed

  private void JbRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbRefreshActionPerformed
    control.listar();
    jlFiltro.setVisible(false);
    JbBuscar.setEnabled(false);
  }//GEN-LAST:event_JbRefreshActionPerformed

  private void jtProdutoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtProdutoMouseClicked
    if (prodTm.getRowCount() > 0 && (jtfId.getText() != null && jtfDescricao != null)) {
      habilitaJb(true, false, true, false, true);
      habilitaJtf(false);
      limpar();
      selecionado();
    }
  }//GEN-LAST:event_jtProdutoMouseClicked

  private void jtfIdKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfIdKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfCodEan.requestFocus();
    }
  }//GEN-LAST:event_jtfIdKeyPressed

  private void jtfCodEanKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfCodEanKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfDescricao.requestFocus();
    }
  }//GEN-LAST:event_jtfCodEanKeyPressed

  private void jtfDescricaoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfDescricaoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfIdEmpresa.requestFocus();
    }
  }//GEN-LAST:event_jtfDescricaoKeyPressed

  private void jtfEmbKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfEmbKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfCodEan.requestFocus();
    }
  }//GEN-LAST:event_jtfEmbKeyPressed

  private void jtfPrecoVendaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfPrecoVendaKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      salvar();
    }
  }//GEN-LAST:event_jtfPrecoVendaKeyPressed

  private void jtfIdEmpresaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfIdEmpresaKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (jtfIdEmpresa.getText().isEmpty()) {
        selecionaEmpresa();
        jtfPrecoVenda.requestFocus();
      } else {
        try{
        Empresa empresa = control.carregaEmpresa(Integer.parseInt(jtfIdEmpresa.getText()));
        jtfIdEmpresa.setText(String.valueOf(empresa.getId()));
        jtfEmpresa.setText(empresa.getRazao());
        } catch (ControllerException | NullPointerException e){
          Util.msgAdv(e, "Não foi localizada nenhuma empresa para o id informado.");
        }
        jtfPrecoVenda.requestFocus();
      }
    } else if (evt.getKeyCode() == KeyEvent.VK_F12) {
      selecionaEmpresa();
    }
  }//GEN-LAST:event_jtfIdEmpresaKeyPressed

  private void jcbAtivoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jcbAtivoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfEmb.requestFocus();
    }
  }//GEN-LAST:event_jcbAtivoKeyPressed

  private void jtProdutoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtProdutoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_SPACE) {
      if (JbBuscar.isEnabled()) {
        control.pesquisar();
      }
    } else if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (modoConsultaExt) {
        selecionaRegistro();
      }
    }
  }//GEN-LAST:event_jtProdutoKeyPressed

  private void jtfDescricaoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfDescricaoKeyReleased
    Util.setFirstLetterUpperCase(jtfDescricao, jtfDescricao.getSelectionStart());
  }//GEN-LAST:event_jtfDescricaoKeyReleased

  private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
    dialog = null;
  }//GEN-LAST:event_formWindowClosed

  private void jtfEmbFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfEmbFocusLost
    jtfEmb.setText(jtfEmb.getText().toUpperCase());
  }//GEN-LAST:event_jtfEmbFocusLost

  private void jbJTableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbJTableActionPerformed
    getLarguraJtBanco();
  }//GEN-LAST:event_jbJTableActionPerformed

  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
          javax.swing.UIManager.setLookAndFeel(info.getClassName());
          break;
        }
      }
    } catch (ClassNotFoundException ex) {
      java.util.logging.Logger.getLogger(ProdutoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
      java.util.logging.Logger.getLogger(ProdutoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
      java.util.logging.Logger.getLogger(ProdutoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(ProdutoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the dialog */
    java.awt.EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        ProdutoJDialog dialog = new ProdutoJDialog(new javax.swing.JFrame(), true);
        dialog.addWindowListener(new java.awt.event.WindowAdapter() {
          @Override
          public void windowClosing(java.awt.event.WindowEvent e) {
            System.exit(0);
          }
        });
        dialog.setVisible(true);
      }
    });
  }
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton JbBuscar;
  private javax.swing.JButton JbCancelar;
  private javax.swing.JButton JbEditar;
  private javax.swing.JButton JbExcluir;
  private javax.swing.JButton JbNovo;
  private javax.swing.JButton JbRefresh;
  private javax.swing.JButton JbRelatorio;
  private javax.swing.JButton JbSalvar;
  private javax.swing.JToolBar JtbMaster;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JLabel jLabel3;
  private javax.swing.JLabel jLabel4;
  private javax.swing.JLabel jLabel5;
  private javax.swing.JLabel jLabel7;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JToolBar.Separator jSeparator1;
  private javax.swing.JToolBar.Separator jSeparator2;
  private javax.swing.JButton jbJTable;
  private javax.swing.JCheckBox jcbAtivo;
  private javax.swing.JLabel jlFiltro;
  private javax.swing.JPanel jpDados;
  private javax.swing.JTable jtProduto;
  private javax.swing.JTextField jtfCodEan;
  private javax.swing.JTextField jtfDescricao;
  private javax.swing.JTextField jtfEmb;
  private javax.swing.JTextField jtfEmpresa;
  private javax.swing.JTextField jtfId;
  private javax.swing.JTextField jtfIdEmpresa;
  private javax.swing.JTextField jtfPrecoVenda;
  // End of variables declaration//GEN-END:variables

  public void novo() {
    limpar();
    habilitaJb(false, true, false, true, false);
    habilitaJtf(true);
    jtfEmb.requestFocus();
  }

  private void getLarguraJtBanco() {
    UsuarioJTableUtil.setUsuarioJTable(prodTm, jtProduto, "jtProduto", Master.usuarioLogado);
  }

  private void selecionaEmpresa() {
    EmpresaJDialog.getInstance(null, true, jtfIdEmpresa, jtfEmpresa).setVisible(true);
  }

  public void selecionado() {
    int linha = jtProduto.getSelectedRow();//grava a linha selecionada
    int linhaSel = jtProduto.convertRowIndexToModel(linha);

    if (linhaSel >= 0) { // executa o procedimento se o JTable não estiver vazio
      int colunaSel = jtProduto.getSelectedColumn(); //grava a coluna selecionada
      boolean pesq = control.setEnabledPesquisa(colunaSel); // Verifica as colunas que serão habilitadas para pesquisa
      jtfId.setText(prodTm.getValueAt(linhaSel, ProdutoTableModel.COLUNA_COD_ID).toString());
      jtfPrecoVenda.setText(prodTm.getValueAt(linhaSel, ProdutoTableModel.COLUNA_COD_PRECO_VENDA).toString());
      jtfEmb.setText(prodTm.getValueAt(linhaSel, ProdutoTableModel.COLUNA_COD_EMBALAGEM).toString());
      jtfCodEan.setText(prodTm.getValueAt(linhaSel, ProdutoTableModel.COLUNA_COD_CODEAN).toString());
      jtfDescricao.setText(prodTm.getValueAt(linhaSel, ProdutoTableModel.COLUNA_COD_DESCRICAO).toString());
      jtfEmpresa.setText(prodTm.getValueAt(linhaSel, ProdutoTableModel.COLUNA_COD_EMPRESA).toString());
      jcbAtivo.setSelected(Boolean.parseBoolean(prodTm.getValueAt(linhaSel, ProdutoTableModel.COLUNA_COD_ATIVO).toString()));
      jtfIdEmpresa.setText(prodTm.getValueAt(linhaSel, ProdutoTableModel.COLUNA_COD_ID_EMPRESA).toString());
      idEmpresa = Integer.parseInt(prodTm.getValueAt(linhaSel, ProdutoTableModel.COLUNA_COD_ID_EMPRESA).toString());

      control.modoConsulta = pesq;
      JbBuscar.setEnabled(pesq);
    }
  }

  public Produto criaObjeto() {
    Produto prod = new Produto();
    prod.setAtivo(jcbAtivo.isSelected());
    prod.setCodEan(jtfCodEan.getText());
    prod.setDescricao(jtfDescricao.getText());
    prod.setEmbalagem(jtfEmb.getText());
    try{
    Empresa empresa = control.carregaEmpresa(Integer.parseInt(jtfIdEmpresa.getText()));
    prod.setEmpresa(empresa);
    } catch (ControllerException e){
      Util.msgErro("O Id da Empresa é inválido");
    }
    if (!jtfId.getText().isEmpty()) {
      prod.setId(Integer.parseInt(jtfId.getText()));
    }
    prod.setPrecoVenda(new BigDecimal(jtfPrecoVenda.getText()));
    
    return prod;
  }

  private void salvar() {
    control.salvar(criaObjeto());
    listar();
    habilitaJb(true, false, false, false, false);
    habilitaJtf(false);
    limpar();
  }

  private void listar() {
    setJtProdutoTm(control.listar());
    limpar();
  }

  private void limpar() {
    jtfCodEan.setText(null);
    jtfDescricao.setText(null);
    jtfEmb.setText(null);
    jtfEmpresa.setText(null);
    jtfId.setText(null);
    jtfIdEmpresa.setText(null);
    jtfPrecoVenda.setText(null);
    jcbAtivo.setSelected(false);
    JbBuscar.setEnabled(false);
    idEnd = 0;
  }

  public void setJtProdutoTm(List<Produto> ct) {
    removeAllJtable();
    if (!ct.isEmpty()) {
      prodTm.adicionaLista(ct);
    }
  }

  public void setJtProdutoTm(Produto ct) {
    removeAllJtable();
    if (ct != null) {
      prodTm.adiciona(ct);
    }
  }

  private void removeAllJtable() {
    while (prodTm.getRowCount() > 0) {
      prodTm.remove(0);
    }
  }

  /**
   * Determina quais os botões da barra de ferramentas ficará ativo
   *
   * @param novo
   * @param salvar
   * @param editar
   * @param cancelar
   * @param excluir
   */
  public void habilitaJb(Boolean novo, Boolean salvar, Boolean editar, Boolean cancelar,
          Boolean excluir) {
    JbNovo.setEnabled(novo);
    JbSalvar.setEnabled(salvar);
    JbEditar.setEnabled(editar);
    JbCancelar.setEnabled(cancelar);
    JbExcluir.setEnabled(excluir);
  }

  /**
   * Define se os JTextFields serão liberados para edição do usuário
   *
   * @param tf <b>True</b> - Habilitar; <b>False</b> - Desabilitar;
   */
  public void habilitaJtf(Boolean tf) {
    jtfEmb.setEnabled(tf);
    jtfCodEan.setEnabled(tf);
    jtfDescricao.setEnabled(tf);
    jtfEmpresa.setEnabled(tf);
    jtfIdEmpresa.setEnabled(tf);
    jtfPrecoVenda.setEnabled(tf);
    jcbAtivo.setEnabled(tf);
  }

  private void editar() {
    habilitaJb(false, true, false, true, false);
    habilitaJtf(true);
    jtfEmb.requestFocus();
  }

  private void excluir() {
    control.excluir(criaObjeto());
    listar();
    limpar();
  }

  private void cancelar() {
    limpar();
    habilitaJb(true, false, false, false, false);
    habilitaJtf(false);
    if (control.modoConsulta) {
      control.modoConsulta = false;
    } else {
      listar();
    }
  }

  private void selecionaRegistro() {
    int linha = jtProduto.getSelectedRow();
    int linhaSel = jtProduto.convertRowIndexToModel(linha);
    idPesquisa.setText(prodTm.getValueAt(linhaSel, ProdutoTableModel.COLUNA_COD_ID).toString());
    razaoPesquisa.setText(prodTm.getValueAt(linhaSel, ProdutoTableModel.COLUNA_COD_DESCRICAO).toString());
    modoConsultaExt = false;
    this.dispose();
  }

  class ThreadReport extends Thread {

    @Override
    public void run() {
      try {
        control.report();
      } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, ex.getMessage());
      }
    }
  }
}
